package com.dxy.lc.manager;

import com.dxy.lc.cache.ExpiringCache;
import com.dxy.lc.cache.ICache;
import com.dxy.lc.model.entity.User;
import com.dxy.lc.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class UserCacheManager {

    public static UserCacheManager INSTANCE;

    private ICache<Integer, User> userCache;

    @Autowired
    private UserMapper userMapper;

    @Value("${cache.conf.user-cache-duration:1}")
    private long userCacheDuration;

    @PostConstruct
    public void init(){
        userCache = new ExpiringCache<Integer, User>()
                .setDuration(userCacheDuration)
                .setTimeUnit(TimeUnit.HOURS)
                .setLoader(this::selectFromDb);
        UserCacheManager.INSTANCE = this;
    }

    @PreDestroy
    public void destroy(){
        ExpiringCache.shutdown();
    }

    private User selectFromDb(Integer id) {
        log.debug("======> user cache select from db, userId: " + id + " <======");
        return userMapper.selectById(id);
    }

    public User getById(Integer id){
        return userCache.get(id);
    }

    public void removeById(Integer id){
        userCache.remove(id);
    }
}
